<?php

namespace app\index\controller;

use think\Controller;
use app\index\model\Region;
use app\warehouse\model\Distribute;
use app\warehouse\model\Freight;
use app\index\model\Cart;

class Ajax extends Controller
{
    //得到省市区json sky
    public function region()
    {
        $type = input('get.type');
        $pid = input('get.pid');
        $target = input('get.target');
        $rs = model('Region')->getRegion($pid);
        
        $regions = array();
        foreach ($rs as $r) {
            $regions[] = array('region_id' => $r['id'], 'region_name' => $r['name']);
        }
        $arr['regions'] = $regions;
        $arr['type'] = $type;
        $arr['target'] = $target;

        return json($arr);
    }

    //获取承运商对应的物流方式 sky
    public function logistics()
    {
        $cid = input('get.cid'); //承运商id
        //$shopId = input('get.shopId'); //店铺ID

        $distributeModel = new Distribute();
        $list = $distributeModel->getLogistics($cid);

        return json($list);
    }

    //计算订单运费 sky
    public function freightCost()
    {
        $warehouseId = input('warehouseid',0);
        $orderAddress = [
            'provinceid'    => input('provinceid'),
            'cityid'        => input('cityid'),
            'townid'        => input('townid')
        ];
        $carrierId = input('carrierId');
        $logisticsId = input('logisticsId');
        $weight = input('weight');
        //$shopId = input('shopId');

        if($warehouseId==0){
            return '卖家没有配置仓库地址';
        }

        $FreightModel = new Freight();
        
        //一个运费配置
        $freightConfig =  $FreightModel->getFeightConfig($warehouseId, $orderAddress, $carrierId, $logisticsId);
        $arrivalData = isset($freightConfig['aging']) ? date('Y-m-d',strtotime($freightConfig['aging'] . " days")) : '';
        
        //运费
        $cost = $FreightModel->getFeightCost($freightConfig, $weight);

        $data = ['cost' => sprintf("%.2f", $cost), 'arrivalData' => $arrivalData];
        return json($data);
    }
}